package campshop.daos;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import campshop.models.CarGoods;
public class CarGoodsDao extends JdbcDaoSupport{
	public long createCar(CarGoods cg)
	{
		String sql = "insert into " +
				"tbl_car_goods (cs_uId, gi_uGoodsId, cg_uGoodsNum)" +
				" values (?, ?, ?)";
		if(super.getJdbcTemplate().update(sql, cg.getuUserId(), cg.getuGoodsId(), cg.getuGoodsNum())>0){
			return super.getJdbcTemplate().queryForInt("select max(cg_uId) from tbl_car_goods");
		}else return 0L;
	}
	
	public boolean addCarGoods(CarGoods cg)
	{
		String sql = "insert into " +
				"tbl_car_goods (cg_uId, cs_uId, gi_uGoodsId, cg_uGoodsNum)" +
				" values (?, ?, ?, ?)";
		if(super.getJdbcTemplate().update(sql, cg.getuCarId(), cg.getuUserId(), cg.getuGoodsId(), cg.getuGoodsNum())>0){
			return true;
		}else return false;
	}
	
	public boolean delCar(long uCarId)
	{
		String sql = "delete from tbl_car_goods where cg_uId = ?";
		if(super.getJdbcTemplate().update(sql, uCarId)>0) return true;
		return false;
	}
	
	public boolean delCarGoods(long uCarId, long uGoodsId)
	{
		String sql = "delete from tbl_car_goods where cg_uId = ? and gi_uGoodsId = ?";
		if(super.getJdbcTemplate().update(sql, uCarId, uGoodsId)>0) return true;
		return false;
	}
	
	public boolean updateCarGoods(CarGoods cg) {
		String sql="update tbl_car_goods " +
				"set cg_uGoodsNum= ? " +
				"where cg_uId = ? and gi_uGoodsId = ?";
		if(super.getJdbcTemplate().update(sql, cg.getuCarId(), cg.getuGoodsId())>0){
			return true;
		}else return false;
	}
	
	public CarGoods getCarGoods(long uCarId, long uGoodsId)
	{
		String sql = "select * from tbl_car_goods where cg_uId=" + uCarId + "and gi_uGoodsId=" + uGoodsId;
		return (CarGoods)super.getJdbcTemplate().queryForObject(sql, new CarGoodsRowMapper());
	}
	
	//一辆购物车可含有多种商品
	public List<CarGoods> getCarGoods(long uCarId)
	{
		String sql = "select * from tbl_car_goods where cg_uId=" + uCarId;
		return super.getJdbcTemplate().query(sql, new CarGoodsRowMapper());
	}
	class CarGoodsRowMapper implements RowMapper<CarGoods>{
		@Override
		public CarGoods mapRow(ResultSet rs, int rowNum) throws SQLException {
			CarGoods cg = new CarGoods();
			cg.setuCarId(rs.getLong("cg_uId"));
			cg.setuUserId(rs.getLong("cs_uId"));
			cg.setuGoodsId(rs.getLong("gi_uGoodsId"));
			cg.setuGoodsNum(rs.getLong("cg_uGoodsNum"));
			return cg;
		}	
	}
}